import { Application } from "egg";
import CodoBase from "../CodoBase";
import { Weaver } from "./type";
import { WeaverAuth } from "./Auth";

/** 泛微工作流api封装 */
export class WeaverWorkflow extends CodoBase {
	constructor(app: Application, private config: Weaver.Config, private token: string) {
		super(app);
	}

	/**
	 *
	 * 获取待处理流程数量
	 * @param {string} workcode 员工工号
	 * @return {string} 待处理流程数量
	 * @memberof WeaverWorkflow
	 */
	async getDoingWorkflowRequestCount(workcode: string) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getDoingWorkflowRequestCount`;
		const res = await this.app.curl<string>(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
		});

		return res.data;
	}

	/** 可创建的流程列表 */
	async getCreateWorkflowList(workcode: string, conditions?: Weaver.Workflow.getCreateWorkflowListRequest) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getCreateWorkflowList`;
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				conditions: JSON.stringify(conditions),
			},
		});

		return JSON.parse(res.data) as Weaver.Workflow.getCreateWorkflowListResponse[];
	}

	/** 获取所有流程列表 */
	async getAllWorkflowRequestList(workcode: string, params?: Weaver.Workflow.getAllWorkflowRequestListRequest) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getAllWorkflowRequestList`;
		const p = {
			...params,
			conditions: params?.conditions ? JSON.stringify(params.conditions) : undefined,
		};
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				...p,
			},
		});

		return JSON.parse(res.data) as Weaver.Workflow.WorkflowRequestListResponse[];
	}

	/** 获取 办结流程列表 */
	async getProcessedWorkflowRequestList(workcode: string, params?: Weaver.Workflow.getAllWorkflowRequestListRequest) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getProcessedWorkflowRequestList`;
		const p = {
			...params,
			conditions: params?.conditions ? JSON.stringify(params.conditions) : undefined,
		};
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				...p,
			},
		});

		return JSON.parse(res.data) as Weaver.Workflow.WorkflowRequestListResponse[];
	}

	/** 获取指定user所发起的流程数据列表 */
	async getMyWorkflowRequestList(workcode: string, params?: Weaver.Workflow.getAllWorkflowRequestListRequest) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getMyWorkflowRequestList`;
		const p = {
			...params,
			conditions: params?.conditions ? JSON.stringify(params.conditions) : undefined,
		};
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				...p,
			},
		});
		return JSON.parse(res.data) as Weaver.Workflow.WorkflowRequestListResponse[];
	}

	/** 获取流程信息详情 */
	async getWorkflowRequest(workcode: string, requestId: string | number) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getWorkflowRequest`;
		const res = await this.app.curl(url, {
			method: "GET",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				requestId,
			},
		});

		return JSON.parse(res.data) as Weaver.Workflow.WorkflowRequestDetail;
	}

	/** 获取流程流转数据 */
	async getRequestOperatorInfo(workcode: string, requestId: string | number) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getRequestOperatorInfo`;
		const res = await this.app.curl(url, {
			method: "GET",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: { requestId },
		});

		return JSON.parse(res.data) as Weaver.Workflow.WorkflowRequestOperatorInfo;
	}

	/** 新建流程
	 * - 1、如果新建流程参数不符合规则、比如mainData 格式错误多个“}、]”则会提示参数错误，一般会提示workflowId为0
	 * - 2、必填字段不允许为空
	 * - 3、参数workflowId对应的流程要有该流程创建权限
	 * - 4、主表、明细表中如果参数不正确（和路径表单字段 字段名称不一致，参数中多了都不允许正常新建流程，并且会提示异常参数）
	 * - 5、附件上传说明，字段值格式如下： 格式为 [{"fieldName":"字段数据库名称","fieldValue":字段值}] 例如：附件上传字段的值为 fieldValue:[{"filePath":"上传的附件地址或者base64","fileName":"附件名称(包含附件类型)"}] 除了附件上传，其余字段类型的字段值都为字段内容
	 * - 6、otherParams参数为map，扩展参数暂时支持如下参数：
	 * - - isnextflow ：新建流程是否默认提交到第二节点，可选值为[0 ：不流转 1：流转 (默认)]
	 * - - delReqFlowFaild：新建流程失败是否默认删除流程，可选值为[0 ：不删除 1：删除 (默认)]
	 * - - requestSecLevel: "流程密级， 开启密级后生效， 默认公开",
	 * - - requestSecValidity:”保密期限，流程密级为秘密或机密时，通过改参数上传保密期限，不上传时取分级保护出的保密期限“
	 * - - isVerifyPer："是否验证用户创建流程权限，可选值为[0 ：不验证 1：验证 (默认)]"
	 */
	async doCreateRequest(workcode: string, params: Weaver.Workflow.DoCreateRequestParams) {
		const url = `${this.config.baseUrl}/api/workflow/paService/doCreateRequest`;
		const p = {
			...params,
			mainData: params?.mainData ? JSON.stringify(params.mainData) : undefined,
			detailData: params?.detailData ? JSON.stringify(params.detailData) : undefined,
			otherParams: params?.otherParams ? JSON.stringify(params.otherParams) : undefined,
		};
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: { ...p },
		});

		return JSON.parse(res.data) as Weaver.Workflow.DoCreateRequestResponse;
	}

	/** 提交流程，新建之后需要提交，提交时可以选择性更新主表详情表数据等 */
	async submitRequest(workcode: string, requestId: string | number, params?: { requestId: string | number }) {
		const url = `${this.config.baseUrl}/api/workflow/paService/submitRequest`;
		const p = {
			...params,
			// @ts-ignore
			detailData: params?.detailData ? JSON.stringify(params.detailData) : undefined,
		};
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: { requestId, ...p },
		});
		return JSON.parse(res.data) as Weaver.Workflow.CommonResponse;
	}

	/** 删除流程 */
	async deleteRequest(workcode: string, requestId: string | number, otherParams?: { ismonitor?: "1" | "0" }) {
		const url = `${this.config.baseUrl}/api/workflow/paService/deleteRequest`;
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				requestId,
				otherParams: otherParams?.ismonitor ? JSON.stringify(otherParams) : undefined,
			},
		});
		return JSON.parse(res.data) as Weaver.Workflow.CommonResponse;
	}

	/** 强制收回 */
	async doForceDrawBack(workcode: string, requestId: string | number, otherParams?: { ismonitor?: "1" | "0" }) {
		const url = `${this.config.baseUrl}/api/workflow/paService/doForceDrawBack`;
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				requestId,
				otherParams: otherParams?.ismonitor ? JSON.stringify(otherParams) : undefined,
			},
		});
		return JSON.parse(res.data) as Weaver.Workflow.CommonResponse;
	}

	/** 强制归档 */
	async doForceOver(workcode: string, requestId: string | number, otherParams?: { ismonitor?: "1" | "0" }) {
		const url = `${this.config.baseUrl}/api/workflow/paService/doForceOver`;
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: {
				requestId,
				otherParams: otherParams?.ismonitor ? JSON.stringify(otherParams) : undefined,
			},
		});
		return JSON.parse(res.data) as Weaver.Workflow.CommonResponse;
	}

	/** 获取流程意见 */
	async getRequestLog(workcode: string, requestId: string | number, params?: { pageSize: number; pageNumber: number }) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getRequestLog`;

		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: { requestId, otherParams: params ? JSON.stringify(params) : undefined },
		});
		return JSON.parse(res.data) as Weaver.Workflow.RequestLogResponse;
	}

	/** 获取流程状态信息 */
	async getRequestStatus(workcode: string, requestId: string | number) {
		const url = `${this.config.baseUrl}/api/workflow/paService/getRequestStatus`;
		const res = await this.app.curl(url, {
			method: "GET",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: { requestId },
		});
		return JSON.parse(res.data) as Weaver.Workflow.GetRequestStatusResponse;
	}

	/** 流程撤回 */
	async withdrawRequest(
		workcode: string,
		params: {
			requestId: string | number;
			/** 撤回流程时，提交的意见 */
			remark?: string;
			/** 是否提醒 0：不提醒 1：提醒 */
			isremind?: "0" | "1";
		}
	) {
		const url = `${this.config.baseUrl}/api/workflow/paService/withdrawRequest`;
		const res = await this.app.curl(url, {
			method: "POST",
			headers: {
				appid: this.config.appid,
				token: this.token,
				workcode: WeaverAuth.publicKeyEncrypt(this.config.ecologyPublicKey, workcode),
				"content-length": "0",
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			dataType: "text",
			data: { ...params },
		});
		return JSON.parse(res.data) as Weaver.Workflow.CommonResponse;
	}
}
